package br.com.spam.pipeline.iu;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.Map.Entry;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import br.com.spam.pipeline.core.ControlSignal;
import br.com.spam.pipeline.phase.Phase;

public class IU_PipelinePhase extends JPanel
{
	private static final long serialVersionUID = 171720902559742658L;

	private JLabel name = new JLabel("Phase: ");
	private JTextField pname = new JTextField();

	private JLabel id = new JLabel("Id Inst: ");
	private JTextField iId = new JTextField();

	private JLabel busy = new JLabel("Ocupado: ");
	private JTextField isBusy = new JTextField();

	private JTextField iInst = new JTextField();
	private JTextArea signals = new JTextArea();

	private final Phase phase;

	public IU_PipelinePhase(Phase phase)
	{
		this.phase = phase;
		this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		this.setBackground(Color.WHITE);
		this.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		this.setPreferredSize(new Dimension(this.getPreferredSize().width, 240));

		GridLayout mainDetailsLayout = new GridLayout(0, 2);
		JPanel mainDetailsPanel = new JPanel();
		mainDetailsPanel.setLayout(mainDetailsLayout);

		mainDetailsPanel.add(this.name);
		mainDetailsPanel.add(this.pname);
		this.pname.setEditable(false);
		this.pname.setBackground(Color.WHITE);

		mainDetailsPanel.add(this.id);
		mainDetailsPanel.add(this.iId);
		this.iId.setEditable(false);
		this.iId.setBackground(Color.WHITE);

		mainDetailsPanel.add(this.busy);
		mainDetailsPanel.add(this.isBusy);
		this.isBusy.setEditable(false);
		this.isBusy.setBackground(Color.WHITE);

		this.add(mainDetailsPanel);

		this.iInst.setEditable(false);
		this.iInst.setBackground(Color.WHITE);
		this.iInst.setMaximumSize(new Dimension(this.iInst.getMaximumSize().width, 30));
		this.add(this.iInst);

		this.signals.setEditable(false);
		this.signals.setBackground(Color.WHITE);
		this.add(this.signals);

		this.add(Box.createVerticalGlue());

		this.update();
	}
	private String getSignalsAsString()
	{
		String controlSignalsAsString = "";
		for (Entry<ControlSignal, Object> signal : this.phase.getControlSignals())
		{
			if (!controlSignalsAsString.isEmpty())
			{
				controlSignalsAsString += "\n";
			}

			controlSignalsAsString += signal.getKey().name() + ": " + signal.getValue();
		}
		return controlSignalsAsString;
	}

	public void update()
	{
		this.pname.setText(this.phase.getPhaseAsString());
		this.iId.setText(this.phase.getCurrentInstruction().getOp());
		this.isBusy.setText(String.valueOf(this.phase.isBusy()));
		this.iInst.setText(this.phase.getCurrentInstruction().getInstructionAsString());
		this.signals.setText(this.getSignalsAsString());
	}
}
